package no.progark.pong;

public class Scoreboard {
	
	private static Scoreboard instance; 
	
	private int p1, p2; //scores for each player
	
	private final int maxPoints = 3;
	
	private boolean isWinner = false;
	
	private Scoreboard(){
		p1 = 0;
		p2 = 0;
	}
	
	public static synchronized Scoreboard getInstance(){
		if(instance==null){
			instance = new Scoreboard();
			return instance;
		}
		return instance;
	}
	
	public void checkWin(){
		isWinner = ( p1 == maxPoints || p2 == maxPoints ? true : false); 
		//System.out.println("p1 is "+ p1+  ", p2 is "+p2 +" and isWinner is "+isWinner);
	}
	
	public boolean haveWinner(){
		return isWinner;
	}
	
	
	public int getP1() {
		return p1;
	}

	public void setP1(int p1) {
		this.p1 = p1;
	}

	public int getP2() {
		return p2;
	}

	public void setP2(int p2) {
		this.p2 = p2;
	}

	/**
	 * 
	 * @param p String identicating player to increment scoreline for, either "p1" or "p2", or "P1" or "P2"
	 * @return whether we have winner or not
	 */
	public boolean incrementScoreAndCheckWin(String p){
		if(p.equalsIgnoreCase("p1")) p1++;
		else{p2++;}
		//System.out.println("SCORE: " + p2);
		checkWin();
		//System.out.println("isWinner: " +isWinner);
		return haveWinner();
	}
	
	/**
	 * 
	 * @return 1 if p1 wins, 2 if p2 wins, 0 if no winner has emerged yet.
	 */
	public int getWinner(){
		if(p1 == maxPoints || p2 == maxPoints)
		return (p1 > p2 ? 1 : 2);
		else return 0;
	}
}
